package com.hzgj.bcl.soa.rpc;

import com.google.common.collect.Lists;

import com.hzgj.bcl.soa.config.ReferenceDef;
import com.hzgj.bcl.soa.config.ServerDef;
import com.hzgj.bcl.soa.registry.RegistryService;
import com.hzgj.bcl.util.lang.StrKit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Objects;

import lombok.Getter;

/**
 * Created by panye on 2015/3/28.
 */
public class ServiceAddress {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Getter
    private List<IpAddress> addresses = Lists.newArrayList();

    public static ServiceAddress getAddress(String url) {
        ServiceAddress serviceAddress = new ServiceAddress();
        String[] urls = url.split(",");
        try {
            if (urls.length == 1) {
                serviceAddress.addAddress(urls[0]);
            } else if (urls.length > 1) {
                for (int i = 0; i < urls.length; i++) {
                    serviceAddress.addAddress(urls[i]);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return serviceAddress;
    }

    public static ServiceAddress getAddress(ReferenceDef referenceDef, RegistryService registryService) {
        String url = referenceDef.getUrl();
        if (StrKit.isBlank(url)) {
            Objects.requireNonNull(registryService);
            return ServiceAddress.getAddress(registryService.look(referenceDef));
        } else {
            return ServiceAddress.getAddress(url);
        }
    }

    private static ServiceAddress getAddress(List<ServerDef> serverDefs) {
        Objects.requireNonNull(serverDefs);
        final ServiceAddress serviceAddress = new ServiceAddress();
        serverDefs.forEach(serverDef -> {
            serviceAddress.addAddress(serverDef.getHost(), serverDef.getPort());
        });
        return serviceAddress;
    }

    public List<IpAddress> list() {
        return addresses;
    }

    public void addAddress(String addr_port) {
        try {
            addresses.add(IpAddress.of(addr_port));
        } catch (UnknownHostException e) {
            logger.error("{}", e);
            throw new RuntimeException(e);
        }
    }

    public void addAddress(String ip, int port) {
        try {
            addresses.add(new IpAddress(InetAddress.getByName(ip), port));
        } catch (UnknownHostException e) {
            logger.error("{}", e);
            throw new RuntimeException(e);
        }
    }
}
